package com.example.shiro_springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/myController")
public class MyController {
    @GetMapping("/userLogin")
    public String userLogin(String name, String pwd,
                            @RequestParam(defaultValue = "false") boolean rememberMe,
                            HttpSession session){
        // 1.获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        // 2.封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(name,pwd,rememberMe);
        // 3.调用login方法，进行登录认证
        try {
            subject.login(token);
            session.setAttribute("user",token.getPrincipal().toString());
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            // 4.登录失败
            return "登录失败";
        }
    }

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @GetMapping("userLoginRm")
    public String userLoginRm(HttpSession session){
        session.setAttribute("user","rememberMe");
        return "main";
    }

    //登录认证验证角色
    @RequiresRoles("admin")
    @GetMapping("userLoginRoles")
    @ResponseBody
    public String userLoginRoles(){
        System.out.println("登录认证验证角色");
        return "验证角色成功";
    }
    //登录认证验证权限
    @RequiresPermissions("user:delete")
    @GetMapping("userPermissions")
    @ResponseBody
    public String userLoginPermission(){
        System.out.println("登录认证验证权限");
        return "验证权限成功";
    }

    public static void main(String[] args) {
//        List<Map> list=new ArrayList<>();
//        list.add(Map.of("id",1,"name", "zhangsan"));
//        list.add(Map.of("name", "wwl"));

        List<String> list=new ArrayList<>();
        list.add("a");
        list.add("b");
        System.out.println(list);
    }
}
